package com.czy.owner.ui.hotshop;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.czy.owner.R;
import com.czy.owner.adapter.BaseRecyclerAdapter;
import com.czy.owner.adapter.GoodsSearchHistoryAdapter;
import com.czy.owner.api.CollectionApi;
import com.czy.owner.api.HotWordsApi;
import com.czy.owner.callback.RecycleViewDivider;
import com.czy.owner.db.DbHelper;
import com.czy.owner.db.SearchTable;
import com.czy.owner.db.UserHelper;
import com.czy.owner.entity.HotWordsModel;
import com.czy.owner.global.Constants;
import com.czy.owner.net.http.HttpManager;
import com.czy.owner.net.listener.HttpOnNextListener;
import com.czy.owner.ui.BaseActivity;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.widget.MyScrollView;
import com.czy.owner.widget.NoScrollRecyclerView;
import com.czy.owner.widget.TagsLayout;

import org.xutils.DbManager;
import org.xutils.db.sqlite.WhereBuilder;
import org.xutils.ex.DbException;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
/**
 * Created by asus
 * 商品搜索历史
 */
public class GoodsSearchHistoryActivity extends BaseActivity {

    @BindView(R.id.tv_title_right)
    TextView tvTitleRight;
    @BindView(R.id.et_goods_search)
    EditText etGoodsSearch;
    @BindView(R.id.iv_clear)
    ImageView ivClear;
    @BindView(R.id.scroll_view)
    MyScrollView scrollView;

    @BindView(R.id.tv_history_clear)
    TextView tvHistoryClear;
    @BindView(R.id.tags_goods_hot_search)
    TagsLayout tagsGoodsHotSearch;

    @BindView(R.id.tv_history_title)
    TextView tvHistoryTitle;
    @BindView(R.id.ll_history_clear)
    LinearLayout llHistoryClear;
    @BindView(R.id.rv_goods_search_history)
    NoScrollRecyclerView rvGoodsSearchHistory;


    private List<SearchTable> historyList = new ArrayList<>();
    private GoodsSearchHistoryAdapter goodsSearchAdapter;
    private DbManager db = null;
    private int position;
    private List<TextView> historyTextViews = new ArrayList<>();
    private  static final int HISTORY_TYPE=1;
    private static final int PLATFORM_TYPE = 0;
    private int goodsType=0;
    private int searchType=0;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_goods_search_history;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        goodsType=getIntent().getIntExtra("goodsType",PLATFORM_TYPE);
        scrollView.setScrollViewLine(new MyScrollView.ScrollViewLine() {
            @Override
            public void onScrollChanged(int l, int t, int oldl, int oldt) {

            }
        });
        if (goodsType==PLATFORM_TYPE){
            searchType=SearchTable.SEARCH_TYPE_PLATFORM_GOODS;
        }
        else {
            searchType=SearchTable.SEARCH_TYPE_STORE_GOODS;
        }
        initHotSearch();
        initSearchHistory();
        etGoodsSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    String searchStr = etGoodsSearch.getText() + "";
                    if (!TextUtils.isEmpty(searchStr)) {
                        InputMethodManager imm = (InputMethodManager) GoodsSearchHistoryActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE);
                        imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                        saveSearchGoods(searchStr);
                        initSearchHistory();
                        searchMessage(searchStr);
                    } else {
                        PhoneUtils.ShowToastMessage(GoodsSearchHistoryActivity.this, getResources().getString(R.string.input_search_goods));
                    }
                }
                return false;
            }


        });
        etGoodsSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String input = s + "";
                if (input.length() > 0) {
                    ivClear.setVisibility(View.VISIBLE);
                } else {

                    ivClear.setVisibility(View.INVISIBLE);
                }
            }
        });
    }

    private void saveSearchGoods(String keyWord) {
        try {
            SearchTable tmpSearch = db.selector(SearchTable.class).where("keyword", "=", keyWord).and("searchtype", "=", searchType).and("useraccount", "=", UserHelper.getInstance().getUserAccount()).findFirst();
            if (tmpSearch == null) {
                SearchTable search = new SearchTable();
                search.setKeyWord(keyWord);
                search.setSearchType(searchType);
                search.setSearchTime(System.currentTimeMillis());
                search.setUserAccount(UserHelper.getInstance().getUserAccount());
                db.saveOrUpdate(search);
            } else {
                tmpSearch.setKeyWord(keyWord);
                tmpSearch.setSearchType(searchType);
                tmpSearch.setSearchTime(System.currentTimeMillis());
                tmpSearch.setUserAccount(UserHelper.getInstance().getUserAccount());
                db.update(tmpSearch);
            }
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    private void initHotSearch() {

        HotWordsApi hotWordsApi = new HotWordsApi(new HttpOnNextListener<List<HotWordsModel>>() {
            @Override
            public void onNext(List<HotWordsModel> list) {
                ViewGroup.MarginLayoutParams lp = new ViewGroup.MarginLayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);

                for (int i = 0; i < list.size(); i++) {
                    View view = View.inflate(GoodsSearchHistoryActivity.this, R.layout.item_hot_search, null);
                    TextView textView = (TextView) view.findViewById(R.id.tv_hot_search);
                    textView.setText(list.get(i).getWords());
                    textView.setTag(i);
                    view.setTag(false);
                    historyTextViews.add(textView);
                    view.setOnClickListener(new View.OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            // TODO Auto-generated method stub
                            TextView tv = (TextView) v.findViewById(R.id.tv_hot_search);
                            String text = tv.getText() + "";
                            etGoodsSearch.setText(text);
                            etGoodsSearch.setSelection(text.length());
                        }
                    });
                    tagsGoodsHotSearch.addView(view, lp);

                }
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                PhoneUtils.ShowToastMessage(GoodsSearchHistoryActivity.this, e.getMessage());
            }
        }, this);
        HttpManager httpManager = HttpManager.getInstance();
            httpManager.doHttpDeal(hotWordsApi);

    }
    private void initSearchHistory() {
        db = DbHelper.getInstance().getDb();
        try {
            historyList = db.selector(SearchTable.class)
                    .where("searchtype", "=", searchType)
                    .and("useraccount", "=", UserHelper.getInstance().getUserAccount())
                    .orderBy("searchTime", true)
                    .limit(10)
                    .findAll();
            if (historyList != null && historyList.size() >0) {
                goodsSearchAdapter = new GoodsSearchHistoryAdapter(this, historyList);
                goodsSearchAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener<SearchTable>() {
                    @Override
                    public void onItemClick(int position, SearchTable o, View view) {
                        etGoodsSearch.setText(o.getKeyWord());
                        etGoodsSearch.setSelection(o.getKeyWord().length());

                    }
                });

                RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
                rvGoodsSearchHistory.setLayoutManager(layoutManager);
                rvGoodsSearchHistory.setAdapter(goodsSearchAdapter);
                rvGoodsSearchHistory.addItemDecoration(new RecycleViewDivider(this, LinearLayoutManager.VERTICAL, R.drawable.shape_recyclerview_divider_decoration));

                tvHistoryTitle.setVisibility(View.VISIBLE);
                llHistoryClear.setVisibility(View.VISIBLE);
                rvGoodsSearchHistory.setVisibility(View.VISIBLE);
            }else {
                tvHistoryTitle.setVisibility(View.GONE);
                llHistoryClear.setVisibility(View.GONE);
                rvGoodsSearchHistory.setVisibility(View.GONE);
            }
        } catch (DbException e) {
            e.printStackTrace();
        }

    }

    private void searchMessage(String searchStr) {
        Intent intent=new Intent(GoodsSearchHistoryActivity.this,GoodsListActivity.class);
        intent.putExtra("fromType",HISTORY_TYPE);
        intent.putExtra("goodsType",goodsType);
        intent.putExtra("searchStr",searchStr);
        intent.putExtra("title",searchStr);
        intent.putExtra("mFromType", Constants.GOODSSOURCE_STORE);
        intent.putExtra("mFromTypeId", "0");
        startActivity(intent);
    }

    @Override
    protected void updateViews() {

    }

    @OnClick({R.id.tv_title_right, R.id.iv_clear, R.id.tv_history_clear})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_title_right:
                finish();
                break;
            case R.id.iv_clear:
                etGoodsSearch.setText("");
                break;
            case R.id.tv_history_clear:
                try {
                    WhereBuilder builder = WhereBuilder.b("searchtype", "=", searchType).and("useraccount", "=", UserHelper.getInstance().getUserAccount());
                    db.delete(SearchTable.class, builder);
                    initSearchHistory();
                } catch (DbException e) {
                    e.printStackTrace();
                }
                break;
        }
    }


}
